/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.gt.web;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.CookieUtils;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.FileUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.gt.entity.GtTecClear;
import com.thinkgem.jeesite.modules.gt.service.GtTecClearService;
import com.thinkgem.jeesite.modules.sys.entity.Area;
import com.thinkgem.jeesite.modules.sys.entity.Dict;
import com.thinkgem.jeesite.modules.sys.service.AreaService;
import com.thinkgem.jeesite.modules.sys.utils.DictUtils;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;

/**
 * 技术明白人信息Controller
 * @author zad
 * @version 2018-03-26
 */
@Controller
@RequestMapping(value = "${frontPath}/gt/gtTecClear")
public class GtTecClearController extends BaseController {

	@Autowired
	private GtTecClearService gtTecClearService;
	@Autowired
	private AreaService areaService;
	
	@ModelAttribute
	public GtTecClear get(@RequestParam(required=false) String id) {
		GtTecClear entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = gtTecClearService.get(id);
		}
		if (entity == null){
			entity = new GtTecClear();
		}
		return entity;
	}
	
	@RequestMapping(value = {"list", ""})
	public String list(GtTecClear gtTecClear, String menuId, HttpServletRequest request, HttpServletResponse response, Model model) {
		
		this.areaService.fetchRegions(model);
		if(null == gtTecClear.getArea() || StringUtils.isBlank(gtTecClear.getArea().getCode()))
		{
			Area area = UserUtils.getUser().getArea();
			gtTecClear.setArea(area);
		}
		
		Page<GtTecClear> page = gtTecClearService.findPage(new Page<GtTecClear>(request, response), gtTecClear); 
		model.addAttribute("page", page);
		
		model.addAttribute("gtTecClear", gtTecClear);
		model.addAttribute("menuId", menuId);
		return "modules/gt/basic/gtTecClearList";
	}

	/**
     * 导出文件
     */
    @RequestMapping("downLoad")
    public void downLoad(String areaId,GtTecClear gtTecClear,String timeStamp, HttpServletRequest request, HttpServletResponse response, Model model) throws IOException{
    	Area area = null;
    	if("undefined".equals(areaId))
    	{
    		areaId = "";
    	}
    	if(!StringUtils.isEmpty(areaId))
		{
			area = this.areaService.get(areaId);
		}
    	
    	response.setCharacterEncoding("utf-8");
    	String fileName = UserUtils.getUser().getArea().getName() + Global.getConfig("exportClearFileName");
    	
    	if(null != area)
    	{
    		fileName = area.getName() + Global.getConfig("exportClearFileName");
    	}
    	
    	fileName += DateUtils.getDate();
        // fileName = URLEncoder.encode(fileName, "UTF-8");
    	
    	// response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename="+ new String((fileName + ".xlsx").getBytes(), "iso-8859-1"));
        
        SXSSFWorkbook wb = new SXSSFWorkbook(-1);
        // turn off auto-flushing and accumulate all rows in memory  
        wb.setCompressTempFiles(true); //使用gzip压缩,减小空间占用  
        Sheet sh = wb.createSheet("林业技术明白人信息");
        OutputStream out = new BufferedOutputStream(response.getOutputStream());
        try { //从数据库中得到结果  
        	
        	
        	
        	if(null == gtTecClear.getArea() || StringUtils.isBlank(gtTecClear.getArea().getCode()))
    		{
        		if(StringUtils.isEmpty(areaId))
        		{
	    			area = UserUtils.getUser().getArea();
	    			gtTecClear.setArea(area);
        		}
        		else
        		{
        			gtTecClear.setArea(area);
        		}
    		}
        	
        	Page<GtTecClear> page = new Page<GtTecClear>();
        	page.setOrderBy("a.update_date");
        	gtTecClear.setPage(page);
        	
        	
        	
            List<GtTecClear> list = this.gtTecClearService.findList(gtTecClear);
            
            if(null == list || list.size() < 1)
            {
	            sh.setColumnWidth(0, 50 * 256);
	        	Row rowHeader = sh.createRow(0);
	            Cell cellHeader = rowHeader.createCell(0);
	            cellHeader.setCellValue("信息提示");
	            
	            Row row = sh.createRow(1);
	            Cell cell = row.createCell(0);  
	            cell.setCellValue("没有找到相关条件的数据。");  
	            
	            ((SXSSFSheet) sh).flushRows();
	            
	            CookieUtils.rememberCookieToken(timeStamp,request,response);
	            //统一写出方法
	            FileUtils.writeWb(wb,out);
            }else
            {
	            
	            //设置每一列的宽度,注意 要乘以256,因为1代表excel中一个字符的1/256的宽度  
	            sh.setColumnWidth(0, 5 * 256);
	            sh.setColumnWidth(1, 10 * 256);
	            sh.setColumnWidth(2, 10 * 256);
	            sh.setColumnWidth(3, 15 * 256);
	            sh.setColumnWidth(4, 22 * 256);
	            sh.setColumnWidth(5, 15 * 256);
	            
	            sh.setColumnWidth(6, 30 * 256);
	            sh.setColumnWidth(7, 20 * 256);
	            Row rowHeader = sh.createRow(0);
	            /*CellStyle headerStyle = rowHeader.getRowStyle();
	            headerStyle.setAlignment(CellStyle.ALIGN_CENTER);*/
	            Cell cellHeader = rowHeader.createCell(0);
	            cellHeader.setCellValue("序号");
	            cellHeader = rowHeader.createCell(1);
	            cellHeader.setCellValue("单位");
	            cellHeader = rowHeader.createCell(2);
	            cellHeader.setCellValue("姓名");
	            cellHeader = rowHeader.createCell(3);
	            cellHeader.setCellValue("技术类型");
	            cellHeader = rowHeader.createCell(4);
	            cellHeader.setCellValue("身份证号");
	            cellHeader = rowHeader.createCell(5);
	            cellHeader.setCellValue("联系方式");
	            
	            cellHeader = rowHeader.createCell(6);
	            cellHeader.setCellValue("家庭住址");
	            cellHeader = rowHeader.createCell(7);
	            cellHeader.setCellValue("备注");
	            
	            // 只取5000条数据
	            /*if(null != list && list.size() > Constant.Join.JOIN_EXPORT_MOST_ROWS)
	            {
	            	list.subList(Constant.Join.JOIN_EXPORT_MOST_ROWS, list.size()).clear();
	            }*/
	            
	            // 序号
	            int size = list.size();
	            for(int i = 0; i < size; i++) {
	            	
	            	// 当前技术明白人
	            	GtTecClear gtClear = list.get(i);
	            	
	                Row row = sh.createRow(i+1);
	                Cell cell = row.createCell(0);  
	                cell.setCellValue(i + 1);
	                cell = row.createCell(1);
	                cell.setCellValue(gtClear.getArea().getName());
	                cell = row.createCell(2);
	                cell.setCellValue(gtClear.getName());  
	                cell = row.createCell(3);
	                cell.setCellValue(DictUtils.getDictLabel(gtClear.getType(), "gt_clear_type", null));
	                cell = row.createCell(4);
	                cell.setCellValue(gtClear.getIdcard());
	                cell = row.createCell(5);
	                cell.setCellValue(gtClear.getTel());
	                
	                cell = row.createCell(6);
	                cell.setCellValue(gtClear.getAddress());
	                
	                cell = row.createCell(7);  
	                cell.setCellValue(gtClear.getRemarks());
	                
	      
	                /*if(i > 0 && (i % 1000 == 0)) {  
	                    ((SXSSFSheet) sh).flushRows();  
	                } */
	            }
	            
	            ((SXSSFSheet) sh).flushRows();
	            
	            CookieUtils.rememberCookieToken(timeStamp,request,response);
	            //统一写出方法
	            FileUtils.writeWb(wb,out);
	            
            }
        } catch(Exception e) {
        	sh.setColumnWidth(0, 50 * 256);
        	Row rowHeader = sh.createRow(0);
            Cell cellHeader = rowHeader.createCell(0);
            cellHeader.setCellValue("信息提示");
            
            Row row = sh.createRow(1);
            Cell cell = row.createCell(0);  
            cell.setCellValue("导出失败，请联系管理员。错误信息：" + e.getMessage());  
            
            e.printStackTrace();
            ((SXSSFSheet) sh).flushRows();
            
            CookieUtils.rememberCookieToken(timeStamp,request,response);
            //统一写出方法
            FileUtils.writeWb(wb,out);
        }  
     // 保存日志
     request.setAttribute("title", "用户" + UserUtils.getUser().getLoginName() + "导出了文件：" + fileName);
    }
	
	@RequestMapping(value = "form")
	public String form(GtTecClear gtTecClear, Model model) {
		
		this.areaService.fetchRegions(model);
		
		// 查询技术员技术类别
		List<Dict> clearTypes = DictUtils.getDictList("gt_clear_type");
		model.addAttribute("clearTypes", clearTypes);
		
		model.addAttribute("gtTecClear", gtTecClear);
		return "modules/gt/basic/gtTecClearForm";
	}

	@RequestMapping(value = "save")
	public String save(GtTecClear gtTecClear,String oper,HttpServletRequest request, HttpServletResponse response, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, gtTecClear)){
			return form(gtTecClear, model);
		}
		

		
		if(StringUtils.isBlank(gtTecClear.getId()))
		{
			// 日志标题
			request.setAttribute("title", "添加技术明白人:" + gtTecClear.getName());
		}else
		{
			// 日志标题
			request.setAttribute("title", "修改技术明白人:" + gtTecClear.getName());
		}
		
		
		
		gtTecClearService.save(gtTecClear);
		addMessage(redirectAttributes, "保存技术明白人信息成功");
		
		if("form".equals(oper))
		{
			return "redirect:"+super.frontPath+"/gt/gtTecClear/form?menuId=" + gtTecClear.getMenuId();
		}
		
		return "redirect:"+super.frontPath+"/gt/gtTecClear?menuId=" + gtTecClear.getMenuId();
	}
	
	@RequestMapping(value = "delete")
	public String delete(GtTecClear gtTecClear,HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		gtTecClearService.delete(gtTecClear);
		addMessage(redirectAttributes, "删除技术明白人信息成功");
		
		
		// 日志标题
		request.setAttribute("title", "删除技术明白人:" + gtTecClear.getId());
		
		
		return "redirect:"+super.frontPath+"/gt/gtTecClear?menuId=" + gtTecClear.getMenuId();
	}

}